import { getUserInfoApi } from '@/api/login'
import { getKey, removeKey, setKey } from '@/utils/common/localStorage'
import { bus } from '@/utils/common/mitt'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  /**
   * 用户信息
   */
  const userInfo = ref(getKey('userInfo') || {})
  /**
   * token
   */
  const token = ref(getKey('token') || '')
  /**
   * refreshToken
   */
  const refreshToken = ref(getKey('refreshToken') || '')
  /**
   * 用户头像
   */
  const image_url = ref(getKey('userInfo') ? getKey('userInfo').image_url : '')
  /**
   * 用户权限路由
   */
  const permissionRouter = ref([])

  /**
   * 清除用户信息
   * 清除token和userinfo
   */
  function clearUserInfo() {
    userInfo.value = {}
    token.value = ''
    permissionRouter.value = []
    removeKey('token')
    removeKey('refreshToken')
    removeKey('userInfo')
  }

  /**
   * 获取用户信息，并且存储到本地
   */
  async function getUserInfo() {
    const res = await getUserInfoApi()
    userInfo.value = res.user
    userInfo.value.image_url =
      userInfo.value.image_url == null
        ? 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        : res.user.image_url
    setKey('userInfo', res.user)
    image_url.value = userInfo.value.image_url

    // 触发事件，传递新的permission
    bus.emit('changePermission', userInfo.value.permission)
  }

  /**
   * 修改用户头像
   */
  function resetGetInfo() {
    removeKey('userInfo')
    userInfo.value = {}
    getUserInfo()
  }

  function changeAvatar(url) {
    getUserInfo()
    userInfo.value.image_url = url
    // 这里添加手动触发响应式更新的代码，通知所有依赖该数据的组件重新渲染
    image_url.value = url
  }

  function updateToken(newToken, newrefreshToken) {
    token.value = newToken
    refreshToken.value = newrefreshToken

    setKey('token', newToken)
    setKey('refreshToken', newrefreshToken)
  }

  return {
    userInfo,
    token,
    clearUserInfo,
    getUserInfo,
    resetGetInfo,
    changeAvatar,
    image_url,
    permissionRouter,
    updateToken,
    refreshToken
  }
})
